
$(function () {
    var url = "http://47.108.197.28:3000/search?keywords="
    $("#input").keyup(function (event) {
        if (event.keyCode == 13) {
            var value = $(this).val();
            if (value.trim()) {
                var httpUrl = url + value;
                ajax(httpUrl, value)

            }
        }
    })
    
    function ajax(httpUrl, value) {
        $ajax({
            url: httpUrl,
            success: res => {
                var result = res.result;

                $('.search-result').remove();
                result.songs.forEach((item, i) => {
                    var { name, id, artists, album, duration } = item;
                    var arr = [];
                    var time = duration / 1000;
                    var m = Math.floor(time / 60 % 60);
                    m = m < 10 ? "0" + m : m;
                    console.log(m)
                    var s = Math.floor(time % 60);
                    s = s < 10 ? "0" + s : s;
                    artists.forEach((k, index) => {
                        // console.log(k)
                        arr.push(k.name)
                    })

                    var template = `
                

                <div class="search-result" data-aid = ${id}>
                    <div>${name}</div>
                    <div>${arr.join("/")}</div>
                    <div>《${album.name}》</div>
                    <div>${m}:${s}</div>

                </div>
                `
                    $(".content").append(template);

                });
                $(".search-result").click(function (event) {
                    var { aid } = event.currentTarget.dataset
                    location.href = `02searchdetail.html?id=${aid}`

                })
                $(".sum").remove()
                var sum = `
                <div class="sum">
                    搜索“${value}”，找到<span>${result.songs.length}</span> 首单曲
                </div>
                `
                $(".middle").prepend(sum)
            }
        })
    }

    var id = location.search.split("=")[1];
    var r = decodeURIComponent(id)
    // console.log(r)
    var search = `http://47.108.197.28:3000/search?keywords=${r}`;
    // console.log(search)
    ajax(search, r)
    $("#input").val(r);
    $(".search>button").click(function(){
        var value = $("#input").val()
        url+=value;
        ajax(url,value)
    })
})